# -*- coding: utf-8 -*-
# @Time    : 2020/12/1 19:57
# @Author  : 帅气可爱的Zevin（小泽同学鸭）
# @FileName: flask_python.py
# @Software: PyCharm
# @Motto: study hard and day day up

from flask import Flask, render_template, request, Response
import random

import database.sqlserver_data_process as db

app = Flask(__name__)

pre_js_file = ""
pre_js_info = ""

shop_id = "S20200001"
p = db.sqlserver_data_process()  # 创建一个对象

shop_order_item_id = ""
shop_order_item_num = ""

customer_order_num = "0"
customer_order_info = ""


@app.route('/products.html')
def products_index():  # 提交客户购买订单 【完】
    global customer_order_num
    global customer_order_info
    return render_template("products.html", users=customer_order_num, users_list=customer_order_info)


num = "2"
list = "1,2,3,4,5"


@app.route('/index.html', methods=['POST', 'GET'])  # 第一个界面，显示数据统计【完】
def _index_index():  # 第一个页面
    p = db.sqlserver_data_process()  # 创建一个对象
    result = p.run_store_produce("EXEC get_whole_profit '{}'".format(shop_id))  # 第一张利润表数据

    DATE1 = str(result[0][0])[5:]
    DATE2 = str(result[1][0])[5:]
    DATE3 = str(result[2][0])[5:]
    DATE4 = str(result[3][0])[5:]
    DATE5 = str(result[4][0])[5:]
    DATE6 = str(result[5][0])[5:]
    DATE7 = str(result[6][0])[5:]

    # 销量
    sale_1 = str(result[0][1])
    sale_2 = str(result[1][1])
    sale_3 = str(result[2][1])
    sale_4 = str(result[3][1])
    sale_5 = str(result[4][1])
    sale_6 = str(result[5][1])
    sale_7 = str(result[6][1])

    # 利润
    in_1 = str(result[0][2])
    in_2 = str(result[1][2])
    in_3 = str(result[2][2])
    in_4 = str(result[3][2])
    in_5 = str(result[4][2])
    in_6 = str(result[5][2])
    in_7 = str(result[6][2])

    result = p.run_store_produce("EXEC find_best_item 'S20200001'")  # 第一张利润表数据

    # 商品名称
    item_1 = str(result[0][0]).replace(' ', '')
    item_2 = str(result[1][0]).replace(' ', '')
    item_3 = str(result[2][0]).replace(' ', '')
    item_4 = str(result[3][0]).replace(' ', '')
    item_5 = str(result[4][0]).replace(' ', '')

    # 销量
    item_sell_1 = result[0][1]
    item_sell_2 = result[1][1]
    item_sell_3 = result[2][1]
    item_sell_4 = result[3][1]
    item_sell_5 = result[4][1]

    result = p.run_store_produce("EXEC find_customer 'S20200001'")  # 第一张利润表数据

    # 客户数量
    customer_num1 = 0
    customer_num2 = 0
    customer_num3 = 0
    customer_num4 = 0
    for i in result:
        if str(i[0]) == '1' or str(i[0]) == '2':
            customer_num1 += int(i[1])
        elif str(i[0]) == '3' or str(i[0]) == '4':
            customer_num2 += int(i[1])
        elif str(i[0]) == '5' or str(i[0]) == '6':
            customer_num3 += int(i[1])
        elif str(i[0]) == '7' or str(i[0]) == '8':
            customer_num4 += int(i[1])

    result = p.run_store_produce("EXEC find_top_3_staff 'S20200001'")  # 第一张利润表数据

    # 员工信息
    staff_id_1 = result[0][0]
    staff_name_1 = result[0][1]
    staff_achieve_1 = result[0][2]
    staff_id_2 = result[1][0]
    staff_name_2 = result[1][1]
    staff_achieve_2 = result[1][2]
    staff_id_3 = result[2][0]
    staff_name_3 = result[2][1]
    staff_achieve_3 = result[2][2]

    p = db.sqlserver_data_process()  # 创建一个对象
    result = p.run_store_produce("EXEC find_shop_order '{}'".format(shop_id))  # 订单号
    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j) + ","
        order_list += "!"

    result = p.run_store_produce("EXEC find_customer_order '{}'".format(shop_id))  # 订单号
    num_in = len(result)
    in_list = ""
    for i in result:
        for j in i:
            in_list = in_list + str(j) + ","
        in_list += "!"

    return render_template('index.html', DATE1=DATE1, DATE2=DATE2, DATE3=DATE3, DATE4=DATE4,
                           DATE5=DATE5, DATE6=DATE6, DATE7=DATE7, sale_1=sale_1,
                           sale_2=sale_2, sale_3=sale_3, sale_4=sale_4, sale_5=sale_5,
                           sale_6=sale_6, sale_7=sale_7, in_1=in_1, in_2=in_2, in_3=in_3,
                           in_4=in_4, in_5=in_5, in_6=in_6, in_7=in_7, item_1=item_1,
                           item_2=item_2, item_3=item_3, item_4=item_4, item_5=item_5,
                           item_sell_1=item_sell_1, item_sell_2=item_sell_2,
                           item_sell_3=item_sell_3, item_sell_4=item_sell_4, item_sell_5=item_sell_5,
                           customer_num1=customer_num1,
                           customer_num2=customer_num2, customer_num3=customer_num3, customer_num4=customer_num4,
                           staff_id_1=staff_id_1, staff_name_1=staff_name_1, staff_achieve_1=staff_achieve_1,
                           staff_id_2=staff_id_2, staff_name_2=staff_name_2, staff_achieve_2=staff_achieve_2,
                           staff_id_3=staff_id_3, staff_name_3=staff_name_3, staff_achieve_3=staff_achieve_3,
                           order_num=num_order, order_list=order_list, num_in=num_in, in_list=in_list)


@app.route('/accounts.html')  # 显示库余量【完】
def get_item():
    result = p.run_store_produce("EXEC find_the_item_left '{}'".format(shop_id))  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template('accounts.html', users=num_order, users_list=order_list)


@app.route("/check_item", methods=['POST', 'GET'])  # 库余量模糊查询【完】
def check_products():
    product_no = request.form.get("product_no")

    if str(product_no).isnumeric():
        result = p.run_store_produce(
            "EXEC find_the_special_item_left_num '{}', '{}'".format(str(shop_id), str(product_no)))  # 返回存在的所有
    else:
        result = p.run_store_produce(
            "EXEC find_the_special_item_left '{}', '{}'".format(str(shop_id), str(product_no)))  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template('accounts.html', users=num_order, users_list=order_list)


@app.route('/add_staff.html')  # 显示所有员工信息【完】
def accounts_index(info=""):
    result = p.run_store_produce("EXEC find_the_staff_4 '{}'".format(shop_id))  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template('add_staff.html', users=num_order, users_list=order_list, show_order=info)


@app.route('/product_manage.html')  # 显示所有商品信息【完】
def product_manage_index(info=""):
    result = p.run_store_produce("EXEC find_all_item")  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template('product_manage.html', users=num_order, users_list=order_list, show_order=info)


@app.route("/check_product", methods=['POST', 'GET'])  # 查找产品【完】
def check_product():
    product_no = request.form.get("product_no")
    global shop_order_item_id
    shop_order_item_id = str(product_no)
    result = p.run_store_produce("EXEC find_the_item '{}'".format(str(product_no)))  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template("product_manage.html", users=num_order, users_list=order_list, temp=product_no)


@app.route("/check_staff", methods=['POST', 'GET'])  # 模糊查找员工【完】
def check_staff():
    staff_no = request.form.get("staff_no")
    result = p.run_store_produce("EXEC find_the_staff '{}', '{}'".format(str(staff_no), shop_id))  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template("add_staff.html", users=num_order, users_list=order_list, temp_value=staff_no)


@app.route("/check_sell", methods=['POST', 'GET'])  # 提交购买订单【差一个库余量不足警告】
def check_sell():
    product_no = request.form.get("product_no")
    product_num = request.form.get("product_num")
    staff_no = request.form.get("staff_no")
    customer_no = request.form.get("customer_no")

    result = p.run_buy("EXEC buy_item_s @customer_id = '{}', @shop_id = '{}', @staff_id = '{}',  "
                       "@item_id = '{}',@item_num = {}".format(customer_no, shop_id, staff_no, product_no,
                                                               int(product_num)))

    global customer_order_num
    global customer_order_info
    if len(product_no) > 2 and len(staff_no) > 2 and len(customer_no) > 2:
        customer_order_num = str(int(customer_order_num) + 1)
        customer_order_info = customer_order_info + str(result[0][0]) + "," + str(result[0][1]) + "," + str(
            result[0][2]) + "," + str(result[0][3]) + "," + str(result[0][4]) + "," + str(result[0][5]) + "," + str(
            result[0][6]) + "!"

    return render_template("products.html", users=customer_order_num, users_list=customer_order_info)


@app.route("/submit_sell", methods=['POST', 'GET'])  # 确定购买订单【完】
def submit_sell():
    p.commit_item()

    global customer_order_num
    global customer_order_info

    customer_order_num = "0"
    customer_order_info = ""
    return Response(_index_index())


@app.route("/cancel_sell", methods=['POST', 'GET'])  # 取消购买订单【完】
def cancel_sell():
    p.cancel_item()
    global customer_order_num
    global customer_order_info

    customer_order_num = "0"
    customer_order_info = ''
    return Response(products_index())


@app.route("/oder_product", methods=['POST', 'GET'])  # 商店提交生产进货订单【完】
def oder_product():
    product_num = request.form.get("NumOfProduct")

    global shop_order_item_num
    shop_order_item_num = product_num

    print(shop_order_item_id, shop_order_item_num)

    result = p.run_store_produce("EXEC insert_product_order_s '{}', '{}', '{}'".format(shop_id, shop_order_item_id,
                                                                                       shop_order_item_num))  # 第一张利润表数据

    print(result)
    if len(str(result)) != 6:
        return Response(product_manage_index("alert('添加失败，同一商品一天内只能提交一次进货订单')"))
    else:
        return Response(_index_index())


@app.route("/add_festival", methods=['POST', 'GET'])  # 添加节日【完】
def add_festival():
    festival_name = request.form.get("festival_name")
    festival_discount = request.form.get("festival_discount")
    start_date = request.form.get("start_date")
    end_date = request.form.get("end_date")

    result = p.run_store_produce(
        "EXEC insert_festival '{}', '{}', '{}', '{}' ".format(festival_name, start_date, end_date,
                                                              festival_discount))  # 第一张利润表数据

    if 'ended in the trigger' in str(result):
        return Response(add_festival_index("alert('添加失败，请检查节日日期是否合理')"))
    else:
        return Response(add_festival_index("alert('添加成功')"))


@app.route("/add_items", methods=['POST', 'GET'])
def add_items():
    product_name = request.form.get("product_name")
    sort = request.form.get("sort")
    price = request.form.get("price")
    cost = request.form.get("cost")

    p.run_store_produce("EXEC add_the_item '{}', '{}', '{}', '{}'".format(product_name, sort, price, cost))

    return Response(add_item_index())


@app.route("/add_staffs", methods=['POST', 'GET'])  # 添加员工【完】
def add_staffs():
    staff_name = request.form.get("staff_name")
    sex = request.form.get("sex")

    result = p.run_store_produce(
        "EXEC add_the_staff '{}', '{}', '{}' ".format(shop_id, staff_name, sex))  # 第一张利润表数据
    return Response(accounts_index("alert('添加成功')"))


@app.route("/delete_staff", methods=['POST', 'GET'])  # 删除员工【完】
def delete_staff():
    staff_no = request.form.get("staff_no")

    # print(staff_no)
    result = p.run_store_produce(
        "EXEC delete_the_staff '{}'".format(staff_no))  # 第一张利润表数据

    if result[0][0] == 1:
        return Response(accounts_index("alert('删除成功')"))
    else:
        return Response(accounts_index("alert('删除失败，员工编号有误')"))


@app.route("/delete_festival", methods=['POST', 'GET'])  # 删除节日【完】
def delete_festival():
    festival_no = request.form.get("festival_no")
    print(festival_no)
    result = p.run_store_produce("EXEC delete_the_festival '{}'".format(festival_no))  # 第一张利润表数据
    if result[0][0] == 1:
        return Response(add_festival_index("alert('删除成功')"))
    else:
        return Response(add_festival_index("alert('删除失败，节日不存在')"))


@app.route("/discount_item", methods=['POST', 'GET'])  # 商品打折【完】
def discount_item():
    item_id = request.form.get("item_id")
    discount = request.form.get("discount")

    result = p.run_store_produce("EXEC item_discount '{}', '{}'".format(item_id, discount))

    if result[0][0] == 1:
        return Response(add_item_index("alert('设置成功')"))
    else:
        return Response(add_item_index("alert('设置失败，商品不存在')"))


@app.route("/delete_item", methods=['POST', 'GET']) # 删除商品【完】
def delete_item():
    item_no = request.form.get("item_no")

    print(item_no)

    result = p.run_store_produce("EXEC delete_item '{}'".format(item_no))

    if result[0][0] == 1:
        return Response(add_item_index("alert('下架成功')"))
    else:
        return Response(add_item_index("alert('下架失败，商品不存在')"))


@app.route("/log_in", methods=['POST', 'GET'])  # 登陆界面【完】
def login():
    account = request.form.get("account")
    password = request.form.get("password")
    print(account, password)
    result = p.run_store_produce("EXEC shop_log_in '{}', '{}'".format(account, password))
    if len(result) != 0:
        global shop_id
        shop_id = account
        return Response(_index_index())
    else:
        return render_template("login.html", info="alert('店长号与商店号不匹配')")


@app.route('/')
def login_index():
    return render_template('login.html')


@app.route('/add_festival.html')  # 显示所有节日信息【完】
def add_festival_index(in_order=""):
    result = p.run_store_produce("EXEC find_all_festival")  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"

    return render_template("add_festival.html", users=num_order, users_list=order_list, show_order=in_order)


@app.route('/add_item.html')
def add_item_index(info=""): # 添加商品【完】
    result = p.run_store_produce("EXEC get_item_info")  # 返回存在的所有商品

    num_order = len(result)
    order_list = ""
    for i in result:
        for j in i:
            order_list = order_list + str(j).replace(' ', '') + ","
        order_list += "!"
    return render_template('add_item.html', users=num_order, users_list=order_list, info=info)


@app.route('/add_staff.html')  # 添加员工【完】
def add_staff_index():
    return Response(accounts_index("alert('添加成功')"))


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)
